<template>
  <div ref="wordCloudContainer" class="word-cloud-container">
    <div
      v-for="(word, index) in processedWords"
      :key="index"
      ref="wordElements"
      class="word-item"
      :style="{
        fontSize: `${word.size}px`,
        color: word.color,
        top: `${word.top}px`,
        left: `${word.left}px`,
        transform: `scale(${word.scale})`,
        transition: 'all 0.3s ease'
      }"
      @mouseenter="handleMouseEnter(index)"
      @mouseleave="handleMouseLeave(index)"
      @click="toSearch(word.text)"
    >
      {{ word.text }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { unref } from 'vue'

const router = useRouter()

// 修改props定义，接收ref类型
const props = defineProps({
  words: {
    type: [Array, Object], // 允许接收数组或ref对象
    default: () => [
      { text: '热搜话题1', weight: 10 },
      { text: '热搜话题2', weight: 8 },
      { text: '热搜话题3', weight: 6 },
      { text: '热搜话题4', weight: 5 },
      { text: '热搜话题5', weight: 4 }
    ]
  }
})

// 使用computed获取实际的words数组
const wordsArray = computed(() => {
  // 如果是ref，使用unref获取值
  const rawWords = unref(props.words)
  return Array.isArray(rawWords) ? rawWords : []
})

const colorPalette = [
  '#1296db',
  '#ff4500',
  '#ff8c00',
  '#2f4f4f',
  '#ff69b4',
  '#32cd32',
  '#1e90ff',
  '#ff6347'
]

const wordCloudContainer = ref(null)
const wordElements = ref([])
const processedWords = ref([])

const isOverlapping = (rect1, rect2) => {
  const padding = 10
  return !(
    rect1.right + padding < rect2.left ||
    rect1.left - padding > rect2.right ||
    rect1.bottom + padding < rect2.top ||
    rect1.top - padding > rect2.bottom
  )
}

const generateWordCloud = async () => {
  await nextTick()
  const container = wordCloudContainer.value
  if (!container) return

  const containerWidth = container.clientWidth
  const containerHeight = container.clientHeight

  // 使用计算属性获取words数组
  const currentWords = wordsArray.value
  const maxWeight = Math.max(...currentWords.map((word) => word.weight))

  const placedWords = []

  processedWords.value = currentWords.map((word, index) => {
    const baseSize = 16
    const sizeRatio = word.weight / maxWeight
    const fontSize = baseSize + sizeRatio * 20

    let attempts = 0
    let positioned = false
    let wordPosition = { top: 0, left: 0 }

    while (!positioned && attempts < 100) {
      wordPosition = {
        top: Math.random() * (containerHeight - fontSize),
        left:
          Math.random() * (containerWidth - (word.text.length * fontSize) / 2)
      }

      const tempDiv = document.createElement('div')
      tempDiv.style.position = 'absolute'
      tempDiv.style.fontSize = `${fontSize}px`
      tempDiv.style.top = `${wordPosition.top}px`
      tempDiv.style.left = `${wordPosition.left}px`
      tempDiv.textContent = word.text
      container.appendChild(tempDiv)

      const wordRect = tempDiv.getBoundingClientRect()
      container.removeChild(tempDiv)

      const collision = placedWords.some((placedWord) =>
        isOverlapping(wordRect, placedWord)
      )

      if (!collision) {
        positioned = true
        placedWords.push(wordRect)
      }

      attempts++
    }

    return {
      text: word.text,
      size: fontSize,
      color: colorPalette[index % colorPalette.length],
      top: wordPosition.top,
      left: wordPosition.left,
      scale: 1,
      originScale: 1
    }
  })
}

// 监听words的变化，重新生成词云
watch(
  wordsArray,
  async () => {
    await generateWordCloud()
  },
  { deep: true }
)

const handleMouseEnter = (index) => {
  processedWords.value[index].scale = 1.5
}

const handleMouseLeave = (index) => {
  processedWords.value[index].scale = 1
}

const toSearch = (text) => {
  router.push('category/sub/?keyword=' + text)
  console.log(text)
}

onMounted(async () => {
  await generateWordCloud()
})
</script>

<style scoped>
.word-cloud-container {
  position: relative;
  width: 100%;
  height: 400px;
  background: linear-gradient(135deg, #f5f7fa 0%, #fefeff 100%);
}

.word-item {
  position: absolute;
  cursor: pointer;
  user-select: none;
  opacity: 0.8;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.word-item:hover {
  z-index: 10;
  opacity: 1;
}
</style>
